package com.seupyy.controller;

import com.seupyy.pojo.Result;
import com.seupyy.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import com.seupyy.pojo.User;
import com.seupyy.service.UserService;
import com.seupyy.utils.JwtUtil;
import com.seupyy.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //用户注册接口
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //前置判断
//        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
//            return Result.error("用户名或者密码不能为空");
//        }
        //调用service进行逻辑处理
        //1.先判断用户是否已经注册过：如果已经注册则报错，否则进行注册
        User user = userService.findUserByName(username);
        if (Objects.nonNull(user)) {
            return Result.error("用户名已经被占用");
        } else {
            //2.注册逻辑
            userService.register(username, password);
            return Result.success("用户注册成功");
        }
    }

    //用户登录接口
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //根据用户名查询User
        User user = userService.findUserByName(username);
        //判断是否查询到
        if (Objects.nonNull(user)) {
            //判断密码是否正确
            //1.获取数据库里面存的加密后的密码
            String userPassword = user.getPassword();
            //2.传进来密码进行加密
            String md5String = Md5Util.getMD5String(password);
            //3.判断二者是否相同
            if (userPassword.equals(md5String)) {
                //生成token
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", user.getId());
                claims.put("username", user.getUsername());
                String token = JwtUtil.genToken(claims);
                //缓存token到redis
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                operations.set(token, token, 24, TimeUnit.HOURS);
                //返回token
                return Result.success(token);
            } else {
                return Result.error("密码错误！");
            }
        }
        return Result.error("用户名不存在~");
    }

    //获取用户详细信息
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        //从请求头中获取token后去解析出username
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        String username = (String) claims.get("username");

        //根据username去查询用户信息
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findUserByName(username);
        if (Objects.isNull(user)) {
            return Result.error("查询无此用户信息");
        }
        return Result.success(user);
    }

    //更新用户信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    //更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam(required = true) @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    //更新用户密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> map, @RequestHeader(name = "Authorization") String token) {
        //前置校验1：传入的map集合不能为空，否则npe
        if (StringUtils.isEmpty(map)) {
            return Result.error("参数错误");
        }
        //旧密码
        String oldPwd = map.get("old_pwd");
        //新密码
        String newPwd = map.get("new_pwd");
        String rePwd = map.get("re_pwd");
        //校验2：三个密码有一个为空，报错处理
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("密码不能为空");
        }
        //校验3：获取表中的密码和输入的原密码是否一致
        //根据username去查询用户信息
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findUserByName(username);
        if (!user.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码输入错误");
        }

        //校验4：新密码不能和原密码一样
        if (newPwd.equals(oldPwd)) {
            return Result.error("新密码不能和原密码相同");
        }

        //校验5：新密码和二次确认密码不一致时报错
        if (!newPwd.equals(rePwd)) {
            return Result.error("新密码和确认密码不一致");
        }

        //处理逻辑
        userService.updatePwd(newPwd);

        //删除redis中的旧token
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }
}
